# pythonCode
# -*- coding: utf-8 -*-
# @Time : 2024/10/29 9:26
# @Author : cyz
# @File : main.py
# @Email : cyz.sh@foxmail.com

import json
import socket

from flask import Flask, request, jsonify, render_template

app = Flask(__name__)

def send_udp_message(message, host='127.0.0.1', port=9999, ):
	# 创建 UDP 套接字
	udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

	# 发送消息
	udp_client.sendto(message.encode('utf-8'), (host, port))

	# 接收响应
	response, _ = udp_client.recvfrom(1024)  # 缓冲区大小为 1024 字节
	print(f"收到服务器响应: {response.decode('utf-8')}")


@app.route('/')
def index():
	return render_template('index.html')

@app.route('/submit', methods=['POST'])
def submit():
	vehicle_id = int(request.form.get('vehicle_id'))
	speed = int(request.form.get('speed'))
	print(vehicle_id, speed)

	myMsg = {vehicle_id: speed}

	send_udp_message(json.dumps(myMsg))

	return jsonify({'vehicle_id': vehicle_id, 'speed': speed})

if __name__ == '__main__':
	app.run(debug=True)
